package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import bean.Customer;
import bean.Employee;
import bean.UserBean;

public class PasswordDAO extends DAO<UserBean> {

	public PasswordDAO(SessionFactory factory) {
		super(factory);
	}
	
	public synchronized OperationResult udpateCustomerPassword(String newPassword,String customerName)
	{
		OperationResult result = new OperationResult();
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		List customers = this.getByAttribute("username", customerName, Customer.class);
		Customer customer = (Customer)customers.get(0);
		if(customer != null)
		{
			customer.setPassword(newPassword);
			session.update(customer);
			tx.commit();
		}
		else
		{
			result.setSuccess(false);
			result.addError("User"+customerName+" does not exist");
			tx.rollback();
		}

		return result;
	}

	public synchronized OperationResult updateCustomerPassword(String newPassword,int id)
	{
		OperationResult result = new OperationResult();
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		Customer customer = (Customer) this.getSession().get(Customer.class, id);
		if(customer != null)
		{
			customer.setPassword(newPassword);
			session.update(customer);
			tx.commit();
		}
		else
		{
			result.setSuccess(false);
			result.addError("Out of date. Please relogin.");
			tx.rollback();
		}
		return result;
	}
	
	public synchronized OperationResult updateEmployeePassword(String newPassword,int id)
	{
		OperationResult result = new OperationResult();
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		Employee employee = (Employee) this.getSession().get(Employee.class, id);
		if(employee != null)
		{
			employee.setPassword(newPassword);
			session.update(employee);
			tx.commit();
		}
		else
		{
			result.setSuccess(false);
			result.addError("Out of date. Please relogin.");
			tx.rollback();
		}
		return result;
	}
}
